import { Component, OnInit, Output, EventEmitter, Input, ViewChild } from '@angular/core';
import { MessagesDTO } from 'src/app/ytt/model/messages-dto';
import { OperationNotification, OperationType } from 'src/app/ytt/util/data/operation-notification';
import { NgForm } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { MessagesService } from 'src/app/ytt/services/messages.service';
import { FormUtil } from 'src/app/ytt/util/form/form-util';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-messages-detail',
  templateUrl: './messages-detail.component.html',
  styleUrls: ['./messages-detail.component.less'],
  providers: [DatePipe],
})
export class MessagesDetailComponent implements OnInit {
  /**
   * 信息
   */
  detailItem: MessagesDTO = this.initFormData(null);

  /**
   * 起止时间
   */
  dateTime: Array<Date>;

  /**
   * 详细窗口是否可见标志
   */
  // tslint:disable-next-line: variable-name
  _visible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<MessagesDTO>>();

  /**
   * 详细窗口可见状态变化事件
   */
  @Output()
  visibleChange = new EventEmitter<boolean>();

  @Input()
  set visible(value: boolean) {
    if (value !== this._visible) {
      this._visible = value;
      this.visibleChange.emit(value);
    }
  }
  get visible(): boolean {
    return this._visible;
  }

  /**
   * 系统配置信息编辑组件
   */
  @ViewChild('eitorForm', null)
  editorForm: NgForm;

  constructor(private msg: NzMessageService, private service: MessagesService, private datePipe: DatePipe) {}

  /**
   * 初始化表单数据
   *
   * @param item 要初始化的数据，为null表示新建
   */
  private initFormData(item?: MessagesDTO): MessagesDTO {
    return {
      id: item ? item.id : null,
      title: item ? item.title : '招聘信息',
      content: item ? item.content : null,
      enterprise: item ? item.enterprise : null,
      effectiveTime: item ? item.effectiveTime : null,
      failureTime: item ? item.failureTime : null,
      type: item ? item.type : null,
    };
  }

  ngOnInit() {
    this.detailItem = this.initFormData(null);
  }

  /**
   * 时间控件修改，点击确定改触发方法
   * @param result 时间值
   * @param operationType 字段值
   */
  changeDate(result: Date, operationType: string): void {
    this.detailItem[operationType] = this.datePipe.transform(result, 'yyyy-MM-dd HH:mm:ss');
  }

  onChange(result: Date): void {
    if (result) {
      this.detailItem.effectiveTime = this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss');
      this.detailItem.failureTime = this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss');
    }
  }

  onOk(result: Date): void {}
  /**
   * 关闭数据详细窗口
   */
  onCancel() {
    this.visible = false;
  }

  /**
   * 验证表单，如果通过则保存
   *
   * @param firstTime 是否第1次调用，是则调用表单验证
   */
  validate(firstTime: boolean): void {
    if (firstTime) {
      FormUtil.validateForm(this.editorForm.form);
    }

    // 异步验证中
    if (this.editorForm.form.status === 'PENDING') {
      setTimeout(() => {
        this.validate(false);
      }, 100);
    } else {
      // 结束验证
      if (this.editorForm.form.valid) {
        this.save();
      }
    }
  }

  /**
   * 保存
   */
  save(): void {
    // 验证表单
    if (!FormUtil.validateForm(this.editorForm.form)) {
      return;
    }
    this.loading = true;
    if (this.detailItem.id) {
      this.service
        .update(this.detailItem, this.detailItem.id)
        .subscribe(data => this.afterItemSaved(data, OperationType.UPDATE), null, () => this.afterCallCompleted());
    } else {
      this.service
        .create(this.detailItem)
        .subscribe(data => this.afterItemSaved(data, OperationType.CREATE), null, () => this.afterCallCompleted());
    }
  }

  /**
   * 创建或修改数据, 父组件会调用该功能进行编辑操作
   *
   * @param item 要编辑的数据，如果为null则表示创建新的数据
   */
  edit(item: MessagesDTO): void {
    this.detailItem = this.initFormData(item);
    this.visible = true;
    // 为了保证ViewChild可以取到值，先设置显示标志，再使用定时器来进行后续操作
    setTimeout(() => {
      FormUtil.resetForm(this.editorForm.form, this.detailItem);
      if (this.detailItem.effectiveTime) {
        this.dateTime = [new Date(this.detailItem.effectiveTime), new Date(this.detailItem.failureTime)];
      } else {
        this.dateTime = [new Date(), new Date()];
      }
    }, 100);
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: MessagesDTO, operation: OperationType): void {
    this.loading = false;
    this.visible = false;
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('数据操作成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
}
